/**
 * 文件系统服务实现
 * 包含Web、Tauri等不同环境的具体实现
 */
import { IFileSystemService, AbstractFileSystemService } from './types.ts';
import {
    FileHandle,
    NovelStructure,
    FileSystemOptions,
    FileSystemChangeCallback
} from '../../types/fileSystem.ts';
import WebPersistence from './WebPersistence.ts';
import TauriPersistence from './TauriPersistence.ts';

/**
 * Web环境文件系统服务实现
 * 基于Web File System Access API
 */
export class WebFileSystemService extends AbstractFileSystemService {
    // 最近访问的文件夹，用于恢复先前会话
    private recentFolders: any[] = [];

    constructor() {
        super('web');
        
        // 初始化时加载最近的文件夹列表
        this.loadRecentFolders();
    }

    /**
     * 加载最近访问的文件夹列表
     */
    private loadRecentFolders(): void {
        this.recentFolders = WebPersistence.getRecentFolders();
        console.log(`加载了${this.recentFolders.length}个最近访问的文件夹`);
    }

    /**
     * 获取最近访问的文件夹列表
     * @returns 最近文件夹列表
     */
    getRecentFolders() {
        return this.recentFolders;
    }

    // 权限管理
    async checkPermission(handle: FileHandle): Promise<boolean> {
        if (!handle._handle) return false;
        
        try {
            // 检查文件句柄权限
            const permission = await handle._handle.queryPermission({ mode: 'readwrite' });
            return permission === 'granted';
        } catch (error) {
            console.error('检查文件权限失败:', error);
            return false;
        }
    }

    async requestPermission(handle: FileHandle): Promise<boolean> {
        if (!handle._handle) return false;
        
        try {
            // 请求文件句柄权限
            const permission = await handle._handle.requestPermission({ mode: 'readwrite' });
            
            // 如果获得权限，持久化存储
            if (permission === 'granted') {
                await WebPersistence.savePermission(handle._handle);
            }
            
            return permission === 'granted';
        } catch (error) {
            console.error('请求文件权限失败:', error);
            return false;
        }
    }

    // 基本文件操作
    async selectFolder(options?: any): Promise<FileHandle | null> {
        try {
            // 显示文件夹选择器
            const dirHandle = await window.showDirectoryPicker();
            
            // 创建文件句柄对象
            const fileHandle: FileHandle = {
                id: crypto.randomUUID(),
                name: dirHandle.name,
                isDirectory: true,
                _handle: dirHandle // 存储原始句柄
            };
            
            // 持久化存储权限
            await WebPersistence.savePermission(dirHandle);
            
            // 重新加载最近文件夹列表
            this.loadRecentFolders();
            
            return fileHandle;
        } catch (error) {
            // 用户取消或发生错误
            console.error('选择文件夹失败:', error);
            return null;
        }
    }

    async createFolder(parent: FileHandle, name: string): Promise<FileHandle> {
        try {
            if (!parent._handle) throw new Error('Invalid parent handle');
            // @ts-ignore
            const dirHandle = await parent._handle.getDirectoryHandle(name, { create: true });
            return {
                id: crypto.randomUUID(),
                name: dirHandle.name,
                isDirectory: true,
                _handle: dirHandle
            };
        } catch (error) {
            console.error(`Failed to create folder '${name}':`, error);
            throw error;
        }
    }

    async createFile(parent: FileHandle, name: string, content: string): Promise<FileHandle> {
        try {
            if (!parent._handle) throw new Error('Invalid parent handle');
            // @ts-ignore
            const fileHandle = await parent._handle.getFileHandle(name, { create: true });

            // 写入内容
            // @ts-ignore
            const writable = await fileHandle.createWritable();
            await writable.write(content);
            await writable.close();

            return {
                id: crypto.randomUUID(),
                name: fileHandle.name,
                isDirectory: false,
                _handle: fileHandle
            };
        } catch (error) {
            console.error(`Failed to create file '${name}':`, error);
            throw error;
        }
    }

    async rename(handle: FileHandle, newName: string): Promise<boolean> {
        // Web File System API 不支持直接重命名
        // 需要创建新文件并删除旧文件实现
        console.warn('Rename operation not directly supported in Web File System API');
        return false;
    }

    async delete(handle: FileHandle): Promise<boolean> {
        try {
            if (!handle._handle) return false;

            const parentDir = handle._handle.parent;
            if (!parentDir) return false;

            if (handle.isDirectory) {
                // @ts-ignore
                await parentDir.removeEntry(handle.name, { recursive: true });
            } else {
                // @ts-ignore
                await parentDir.removeEntry(handle.name);
            }
            return true;
        } catch (error) {
            console.error(`Failed to delete '${handle.name}':`, error);
            return false;
        }
    }

    // 内容读写
    async readTextFile(handle: FileHandle, options?: FileSystemOptions): Promise<string> {
        try {
            if (!handle._handle || handle.isDirectory) throw new Error('Invalid file handle');
            // @ts-ignore
            const file = await handle._handle.getFile();
            return await file.text();
        } catch (error) {
            console.error(`Failed to read file '${handle.name}':`, error);
            throw error;
        }
    }

    async writeTextFile(handle: FileHandle, content: string, options?: FileSystemOptions): Promise<void> {
        try {
            if (!handle._handle || handle.isDirectory) throw new Error('Invalid file handle');
            // @ts-ignore
            const writable = await handle._handle.createWritable();
            await writable.write(content);
            await writable.close();
        } catch (error) {
            console.error(`Failed to write to file '${handle.name}':`, error);
            throw error;
        }
    }

    // 结构操作
    async listContents(handle: FileHandle): Promise<FileHandle[]> {
        try {
            if (!handle._handle || !handle.isDirectory) throw new Error('Invalid directory handle');

            const entries: FileHandle[] = [];
            // @ts-ignore
            for await (const [name, entry] of handle._handle.entries()) {
                const isDirectory = entry.kind === 'directory';
                entries.push({
                    id: crypto.randomUUID(),
                    name,
                    isDirectory,
                    _handle: entry
                });
            }
            return entries;
        } catch (error) {
            console.error(`Failed to list contents of '${handle.name}':`, error);
            throw error;
        }
    }

    async scanNovelStructure(rootFolder: FileHandle): Promise<NovelStructure> {
        try {
            if (!rootFolder.isDirectory) throw new Error('Root folder must be a directory');

            // 扫描卷文件夹
            const volumeFolders = await this.listContents(rootFolder);
            const volumes: Array<{
                folder: FileHandle;
                chapters: Array<{
                    file: FileHandle;
                    content?: string;
                }>
            }> = [];

            // 仅处理文件夹作为卷
            for (const volumeFolder of volumeFolders.filter(f => f.isDirectory)) {
                // 扫描章节文件
                const chapterFiles = await this.listContents(volumeFolder);
                const chapters: Array<{
                    file: FileHandle;
                    content?: string;
                }> = [];

                // 仅处理文件作为章节
                for (const chapterFile of chapterFiles.filter(f => !f.isDirectory)) {
                    chapters.push({
                        file: chapterFile
                        // 懒加载内容，不立即读取
                    });
                }

                // 添加卷及其章节
                volumes.push({
                    folder: volumeFolder,
                    chapters
                });
            }

            return {
                rootFolder,
                volumes
            };
        } catch (error) {
            console.error('Failed to scan novel structure:', error);
            throw error;
        }
    }

    // 持久化
    serializeHandle(handle: FileHandle): string {
        // Web环境下无法直接序列化DOM对象，存储基本信息
        const serialized = {
            id: handle.id,
            name: handle.name,
            isDirectory: handle.isDirectory,
            // 无法序列化原始handle
        };
        return JSON.stringify(serialized);
    }

    async deserializeHandle(serialized: string): Promise<FileHandle | null> {
        try {
            const data = JSON.parse(serialized);
            // Web环境下无法恢复原始handle
            // 用户需要重新选择文件夹
            console.warn('Web File System API cannot deserialize handles across sessions');
            return null;
        } catch (error) {
            console.error('Failed to deserialize handle:', error);
            return null;
        }
    }

    // 可选的监控功能
    async beginWatchChanges?(handle: FileHandle, callback: FileSystemChangeCallback): Promise<void> {
        if (!handle._handle || !handle.isDirectory) {
            console.warn('File watching requires valid directory handle');
            return;
        }

        try {
            // 为每个监控的文件夹创建一个唯一ID
            const watchId = `watch_${handle.id}`;
            
            // 存储当前目录下所有文件的最后修改信息
            const fileStates = new Map<string, { lastModified: number, size: number }>();
            
            // 初始扫描
            const entries = await this.listContents(handle);
            
            // 对于Web环境，我们需要手动实现轮询检查文件变化
            for (const entry of entries) {
                if (!entry._handle) continue;
                
                try {
                    // 获取文件信息
                    const file = await entry._handle.getFile();
                    fileStates.set(entry.id, {
                        lastModified: file.lastModified,
                        size: file.size
                    });
                } catch (error) {
                    // 可能是目录或访问权限问题，跳过
                    continue;
                }
            }
            
            // 存储扫描间隔ID
            const intervalId = setInterval(async () => {
                try {
                    // 重新扫描目录
                    const currentEntries = await this.listContents(handle);
                    
                    // 检查新增和修改的文件
                    for (const entry of currentEntries) {
                        if (!entry._handle || entry.isDirectory) continue;
                        
                        try {
                            const file = await entry._handle.getFile();
                            const oldState = fileStates.get(entry.id);
                            
                            if (!oldState) {
                                // 新文件
                                fileStates.set(entry.id, {
                                    lastModified: file.lastModified,
                                    size: file.size
                                });
                                callback('create', entry);
                            } else if (
                                oldState.lastModified !== file.lastModified ||
                                oldState.size !== file.size
                            ) {
                                // 文件已修改
                                fileStates.set(entry.id, {
                                    lastModified: file.lastModified,
                                    size: file.size
                                });
                                callback('modify', entry);
                            }
                        } catch (error) {
                            continue;
                        }
                    }
                    
                    // 检查删除的文件
                    const currentIds = new Set(currentEntries.map(e => e.id));
                    for (const [id, state] of fileStates.entries()) {
                        if (!currentIds.has(id)) {
                            // 文件已删除
                            const deletedHandle: FileHandle = {
                                id,
                                name: id.split('/').pop() || '',
                                isDirectory: false
                            };
                            callback('delete', deletedHandle);
                            fileStates.delete(id);
                        }
                    }
                } catch (error) {
                    console.error('Error during file watch polling:', error);
                }
            }, 2000); // 每2秒检查一次变化
            
            // 存储轮询间隔ID，以便后续清理
            (this as any)._watchIntervals = (this as any)._watchIntervals || new Map();
            (this as any)._watchIntervals.set(watchId, intervalId);
            
            console.log(`Started file watching for ${handle.name} with ID ${watchId}`);
        } catch (error) {
            console.error('Failed to start file watching:', error);
        }
    }

    async endWatchChanges?(handle: FileHandle): Promise<void> {
        if (!handle.id) return;
        
        try {
            const watchId = `watch_${handle.id}`;
            
            // 清理轮询间隔
            if ((this as any)._watchIntervals && (this as any)._watchIntervals.has(watchId)) {
                clearInterval((this as any)._watchIntervals.get(watchId));
                (this as any)._watchIntervals.delete(watchId);
                console.log(`Stopped file watching for ${handle.name} with ID ${watchId}`);
            }
        } catch (error) {
            console.error('Failed to stop file watching:', error);
        }
    }
}

/**
 * Tauri环境文件系统服务实现
 * 基于Tauri API
 */
export class TauriFileSystemService extends AbstractFileSystemService {
    // 最近访问的路径，用于恢复先前会话
    private recentPaths: any[] = [];

    constructor() {
        super('tauri');
        
        // 初始化时加载最近的路径列表
        this.loadRecentPaths();
    }

    /**
     * 加载最近访问的路径列表
     */
    private loadRecentPaths(): void {
        this.recentPaths = TauriPersistence.getRecentPaths();
        console.log(`加载了${this.recentPaths.length}个最近访问的路径`);
    }

    /**
     * 获取最近访问的路径列表
     * @returns 最近路径列表
     */
    getRecentPaths() {
        return this.recentPaths;
    }

    // 权限管理 - Tauri依赖操作系统权限
    async checkPermission(handle: FileHandle): Promise<boolean> {
        // Tauri使用系统权限，不需要额外检查
        return true;
    }

    async requestPermission(handle: FileHandle): Promise<boolean> {
        // Tauri使用系统权限，不需要额外请求
        return true;
    }

    // 基本文件操作
    async selectFolder(options?: any): Promise<FileHandle | null> {
        try {
            // 如果Tauri API可用
            if (window.__TAURI__) {
                const selected = await window.__TAURI__.dialog.open({
                    directory: true,
                    multiple: false,
                    ...options
                });

                if (!selected) return null;

                const path = selected as string;
                const name = path.split('/').pop() || path.split('\\').pop() || 'Unknown';

                // 保存路径到持久存储
                TauriPersistence.savePath(path, name, true);
                
                // 重新加载最近路径列表
                this.loadRecentPaths();

                return {
                    id: path, // 在Tauri中使用路径作为ID
                    name,
                    path,
                    isDirectory: true
                };
            }
            throw new Error('Tauri API not available');
        } catch (error) {
            console.error('Failed to select folder:', error);
            return null;
        }
    }

    async createFolder(parent: FileHandle, name: string): Promise<FileHandle> {
        try {
            if (!parent.path) throw new Error('Invalid parent path');

            const newPath = `${parent.path}/${name}`;
            await window.__TAURI__.fs.createDir(newPath, { recursive: true });

            return {
                id: newPath,
                name,
                path: newPath,
                isDirectory: true
            };
        } catch (error) {
            console.error(`Failed to create folder '${name}':`, error);
            throw error;
        }
    }

    async createFile(parent: FileHandle, name: string, content: string): Promise<FileHandle> {
        try {
            if (!parent.path) throw new Error('Invalid parent path');

            const newPath = `${parent.path}/${name}`;
            await window.__TAURI__.fs.writeTextFile(newPath, content);

            return {
                id: newPath,
                name,
                path: newPath,
                isDirectory: false
            };
        } catch (error) {
            console.error(`Failed to create file '${name}':`, error);
            throw error;
        }
    }

    async rename(handle: FileHandle, newName: string): Promise<boolean> {
        try {
            if (!handle.path) return false;

            const dirPath = handle.path.substring(0, handle.path.lastIndexOf('/'));
            const newPath = `${dirPath}/${newName}`;

            await window.__TAURI__.fs.renameFile(handle.path, newPath);
            return true;
        } catch (error) {
            console.error(`Failed to rename '${handle.name}':`, error);
            return false;
        }
    }

    async delete(handle: FileHandle): Promise<boolean> {
        try {
            if (!handle.path) return false;

            if (handle.isDirectory) {
                await window.__TAURI__.fs.removeDir(handle.path, { recursive: true });
            } else {
                await window.__TAURI__.fs.removeFile(handle.path);
            }
            return true;
        } catch (error) {
            console.error(`Failed to delete '${handle.name}':`, error);
            return false;
        }
    }

    // 内容读写
    async readTextFile(handle: FileHandle, options?: FileSystemOptions): Promise<string> {
        try {
            if (!handle.path || handle.isDirectory) throw new Error('Invalid file path');
            return await window.__TAURI__.fs.readTextFile(handle.path);
        } catch (error) {
            console.error(`Failed to read file '${handle.name}':`, error);
            throw error;
        }
    }

    async writeTextFile(handle: FileHandle, content: string, options?: FileSystemOptions): Promise<void> {
        try {
            if (!handle.path || handle.isDirectory) throw new Error('Invalid file path');
            await window.__TAURI__.fs.writeTextFile(handle.path, content);
        } catch (error) {
            console.error(`Failed to write to file '${handle.name}':`, error);
            throw error;
        }
    }

    // 结构操作
    async listContents(handle: FileHandle): Promise<FileHandle[]> {
        try {
            if (!handle.path || !handle.isDirectory) throw new Error('Invalid directory path');

            // 首先检查缓存中是否有内容
            const cachedContents = TauriPersistence.getCachedDirectoryContents(handle.path);
            if (cachedContents) {
                console.log(`使用缓存的目录内容: ${handle.path}`);
                return cachedContents;
            }

            // 从文件系统读取
            const entries = await window.__TAURI__?.fs.readDir(handle.path);
            
            if (!entries) return [];
            
            const result = entries.map(entry => ({
                id: entry.path,
                name: entry.name || 'Unknown',
                path: entry.path,
                isDirectory: entry.children !== undefined
            }));
            
            // 缓存结果以提高性能
            TauriPersistence.cacheDirectoryContents(handle.path, result);
            
            return result;
        } catch (error) {
            console.error(`Failed to list contents of '${handle.name}':`, error);
            throw error;
        }
    }

    async scanNovelStructure(rootFolder: FileHandle): Promise<NovelStructure> {
        try {
            if (!rootFolder.isDirectory) throw new Error('Root folder must be a directory');

            // 扫描卷文件夹
            const volumeFolders = await this.listContents(rootFolder);
            const volumes: Array<{
                folder: FileHandle;
                chapters: Array<{
                    file: FileHandle;
                    content?: string;
                }>
            }> = [];

            // 仅处理文件夹作为卷
            for (const volumeFolder of volumeFolders.filter(f => f.isDirectory)) {
                // 扫描章节文件
                const chapterFiles = await this.listContents(volumeFolder);
                const chapters: Array<{
                    file: FileHandle;
                    content?: string;
                }> = [];

                // 仅处理文件作为章节
                for (const chapterFile of chapterFiles.filter(f => !f.isDirectory)) {
                    chapters.push({
                        file: chapterFile
                        // 懒加载内容，不立即读取
                    });
                }

                // 添加卷及其章节
                volumes.push({
                    folder: volumeFolder,
                    chapters
                });
            }

            return {
                rootFolder,
                volumes
            };
        } catch (error) {
            console.error('Failed to scan novel structure:', error);
            throw error;
        }
    }

    // 持久化
    serializeHandle(handle: FileHandle): string {
        // Tauri环境仅需保存路径即可
        return JSON.stringify({
            id: handle.id,
            name: handle.name,
            path: handle.path,
            isDirectory: handle.isDirectory
        });
    }

    async deserializeHandle(serialized: string): Promise<FileHandle | null> {
        try {
            const data = JSON.parse(serialized);

            // 检查路径是否仍然存在
            if (data.path) {
                const exists = await window.__TAURI__.fs.exists(data.path);
                if (exists) {
                    return {
                        id: data.path,
                        name: data.name,
                        path: data.path,
                        isDirectory: data.isDirectory
                    };
                }
            }
            return null;
        } catch (error) {
            console.error('Failed to deserialize handle:', error);
            return null;
        }
    }

    // 可选的监控功能
    async beginWatchChanges?(handle: FileHandle, callback: FileSystemChangeCallback): Promise<void> {
        if (!handle.path || !handle.isDirectory) {
            console.warn('File watching requires valid directory path');
            return;
        }

        try {
            // 为每个监控的文件夹创建一个唯一ID
            const watchId = `watch_${handle.id}`;
            
            // 获取初始文件列表状态
            const initialFiles = await this.listContents(handle);
            const fileStates = new Map<string, { name: string, path: string }>();
            
            for (const file of initialFiles) {
                if (!file.path) continue;
                fileStates.set(file.path, {
                    name: file.name,
                    path: file.path
                });
            }
            
            // 在Tauri中，我们使用定时器轮询文件系统状态
            // 在生产版本中，可以使用Tauri的文件系统监控API
            const intervalId = setInterval(async () => {
                try {
                    // 获取当前文件列表
                    const currentFiles = await this.listContents(handle);
                    const currentPaths = new Set<string>();
                    
                    // 检查新增和可能被修改的文件
                    for (const file of currentFiles) {
                        if (!file.path) continue;
                        
                        currentPaths.add(file.path);
                        
                        // 检查是否为新文件
                        if (!fileStates.has(file.path)) {
                            // 新增文件
                            fileStates.set(file.path, {
                                name: file.name,
                                path: file.path
                            });
                            callback('create', file);
                        } else {
                            // 对于已存在的文件，需要检查内容是否变化
                            // 在不支持efficient版本中，我们仅检查非目录文件
                            if (!file.isDirectory) {
                                try {
                                    // 检查文件内容变化
                                    // 这在Tauri中可以通过文件元数据API优化
                                    const oldFileStat = await window.__TAURI__?.fs.metadata(file.path);
                                    const currentFileStat = await window.__TAURI__?.fs.metadata(file.path);
                                    
                                    if (oldFileStat?.modifiedAt !== currentFileStat?.modifiedAt ||
                                        oldFileStat?.size !== currentFileStat?.size) {
                                        callback('modify', file);
                                    }
                                } catch (error) {
                                    // 忽略可能的错误（例如，文件可能刚刚被删除）
                                }
                            }
                        }
                    }
                    
                    // 检查删除的文件
                    for (const [path, fileInfo] of fileStates.entries()) {
                        if (!currentPaths.has(path)) {
                            // 文件已删除
                            const deletedHandle: FileHandle = {
                                id: path,
                                name: fileInfo.name,
                                path: path,
                                isDirectory: false
                            };
                            callback('delete', deletedHandle);
                            fileStates.delete(path);
                        }
                    }
                } catch (error) {
                    console.error('Error during Tauri file watch polling:', error);
                }
            }, 2000); // 每2秒检查一次变化
            
            // 存储轮询间隔ID，以便后续清理
            (this as any)._tauriWatchIntervals = (this as any)._tauriWatchIntervals || new Map();
            (this as any)._tauriWatchIntervals.set(watchId, intervalId);
            
            console.log(`Started Tauri file watching for ${handle.name} with ID ${watchId}`);
        } catch (error) {
            console.error('Failed to start Tauri file watching:', error);
        }
    }

    async endWatchChanges?(handle: FileHandle): Promise<void> {
        if (!handle.id) return;
        
        try {
            const watchId = `watch_${handle.id}`;
            
            // 清理轮询间隔
            if ((this as any)._tauriWatchIntervals && (this as any)._tauriWatchIntervals.has(watchId)) {
                clearInterval((this as any)._tauriWatchIntervals.get(watchId));
                (this as any)._tauriWatchIntervals.delete(watchId);
                console.log(`Stopped Tauri file watching for ${handle.name} with ID ${watchId}`);
            }
        } catch (error) {
            console.error('Failed to stop Tauri file watching:', error);
        }
    }
}

/**
 * 降级实现 - 用于不支持高级文件API的环境
 */
export class FallbackFileSystemService extends AbstractFileSystemService {
    constructor() {
        super('fallback');
    }

    // 实现一个最小功能集，可能会有限制
    // 这里省略实现细节，保持一个框架

    async checkPermission(handle: FileHandle): Promise<boolean> {
        return false;
    }

    async requestPermission(handle: FileHandle): Promise<boolean> {
        return false;
    }

    async selectFolder(options?: any): Promise<FileHandle | null> {
        alert('当前环境不支持文件系统操作');
        return null;
    }

    async createFolder(parent: FileHandle, name: string): Promise<FileHandle> {
        throw new Error('当前环境不支持文件系统操作');
    }

    async createFile(parent: FileHandle, name: string, content: string): Promise<FileHandle> {
        throw new Error('当前环境不支持文件系统操作');
    }

    async rename(handle: FileHandle, newName: string): Promise<boolean> {
        return false;
    }

    async delete(handle: FileHandle): Promise<boolean> {
        return false;
    }

    async readTextFile(handle: FileHandle, options?: FileSystemOptions): Promise<string> {
        throw new Error('当前环境不支持文件系统操作');
    }

    async writeTextFile(handle: FileHandle, content: string, options?: FileSystemOptions): Promise<void> {
        throw new Error('当前环境不支持文件系统操作');
    }

    async listContents(handle: FileHandle): Promise<FileHandle[]> {
        return [];
    }

    async scanNovelStructure(rootFolder: FileHandle): Promise<NovelStructure> {
        throw new Error('当前环境不支持文件系统操作');
    }

    serializeHandle(handle: FileHandle): string {
        return '';
    }

    async deserializeHandle(serialized: string): Promise<FileHandle | null> {
        return null;
    }
}

/**
 * 文件系统服务工厂类
 * 用于创建适合当前环境的文件系统服务实例
 */
export class FileSystemServiceFactory {
    /**
     * 创建并返回适合当前环境的文件系统服务实例
     */
    static create(): IFileSystemService {
        // 检测当前运行环境

        // 1. 检查是否在Tauri环境中
        if (typeof window !== 'undefined' && 'window' in globalThis && window.__TAURI__) {
            console.log('创建Tauri文件系统服务');
            return new TauriFileSystemService();
        }

        // 2. 检查是否支持Web File System Access API
        if (typeof window !== 'undefined' &&
            'window' in globalThis &&
            'showDirectoryPicker' in window) {
            console.log('创建Web文件系统服务');
            return new WebFileSystemService();
        }

        // 3. 降级实现
        console.warn('当前环境不支持高级文件系统API，使用降级实现');
        return new FallbackFileSystemService();
    }
} 